package plot
{
	import mx.collections.ArrayCollection;
	import mx.controls.Label;
	import mx.core.UIComponent;

	public class Grid extends UIComponent
	{
		[Bindable]
		public var lineThickness:int = 2;
		
		[Bindable]
		public var color:uint = 0x000000;
		
		[Bindable]
		public var opacity:Number = 1.0;
		
		[Bindable]
		/**
		 * Indent from the grid lines to the text
		 */
		public var verticalTextIndent:int = 5;
		
		[Bindable]
		public var horizontalTextIndent:int = -5;
		
		private var axisCount:int = 0;
		private var _labels:ArrayCollection = new ArrayCollection();
		
		[Bindable]
		public function get axesProvider():ArrayCollection {
			return _axesProvider;
		}
		public function set axesProvider(value:ArrayCollection):void {
			_axesProvider = value;
			addLabels();
		}
		private var _axesProvider:ArrayCollection;
		
		private var _labelHeight:int = 21;
		private var _labelWidth:int = 100;
		
		public function Grid()
		{
			super(); 
			
			this.percentHeight = 100;
			this.percentWidth = 100;
		}
		
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
			trace("updating grid");
			graphics.clear();
			
			if (axesProvider == null || axesProvider.length == 0)
			return;
			
			axisCount = axesProvider.length;
			
			var colWidth:int = unscaledWidth / (axisCount - 1);
			graphics.lineStyle(lineThickness, color, opacity);
			graphics.moveTo(0, 0);
			
			for (var i:int; i < axisCount ; i++)
			{
				graphics.lineTo(i * colWidth, unscaledHeight - verticalTextIndent - _labelHeight);
				graphics.moveTo(i * colWidth + colWidth, 0);	
			}
			
			var label:Label;
			for (i = 0; i < axisCount; i++)
			{
				label = _labels[i];
				label.move(i * colWidth + horizontalTextIndent, unscaledHeight - label.height);
			}
		}
		
		private function addLabels():void
		{
			var label:Label;
        	
        	for (var i:int; i < axesProvider.length; i++)
        	{
        		label = new Label();
        		label.text = axesProvider[i];
        		label.setStyle("paddingLeft", 0);
        		label.setStyle("paddingRight", 0);
        		label.setStyle("paddingTop", 0);
        		label.setStyle("paddingBottom", 0);
        		
//        		label.percentWidth = 100;
//        		label.percentHeight = 100;
        		label.width = _labelWidth;
        		label.height = 21;
        		
        		addChild(label);
        		_labels.addItem(label);
        	}
		} 
		
	}
}